package com.cd.controller;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.cd.bean.Contact;
import com.cd.bean.Cooperation;
import com.cd.bean.News;
import com.cd.service.contact.ContactService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 *联系我们
 *@Author zhk
 *@Date 2017-12-28
 **/
@RequestMapping("/con")
@Controller
public class ContactController {

	@Autowired
	private ContactService contactService; 
	
	
	/**
	 * 查询（带分页）
	 * @param pn
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/listCon")
	public ModelAndView findAllContact(@RequestParam(value = "pn",defaultValue="1")Integer pn) throws Exception {
		ModelAndView mv = new ModelAndView();
		/*PageHelper.startPage(pn, 8);//开始分页
	    List<Contact> list = contactService.listAll();
		PageInfo page = new PageInfo(list,5);//设置分页信息
*/		
		List<Contact> varlist = contactService.listLimit();
		//mv.addObject("pageInfo", page);
		mv.addObject("varlist", varlist);
		mv.setViewName("info/lxwm/lxwm");
		return mv;
	}
	
	/**
	 * 通过id查询
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/findById")
	public ModelAndView findById(@RequestParam(value = "id") Integer id) throws Exception {
		ModelAndView mv = new ModelAndView();
		Contact con = null;
		Contact nextCon = null;
		Contact preCon = null;
		int total = contactService.size();//获取总记录
		int nextId = id+1;
		int preId = id-1;
		if(id <= total){
			if(id >= 1){
				con = contactService.findById(id);//当前条
				preCon = contactService.findById(preId);//前一条
				nextCon = contactService.findById(nextId);//下一条	
			}else {
				con = contactService.findById(id+1);
			}
		}else{
			con = contactService.findById(id-1);
		}
		
		mv.addObject("con", con);
		mv.addObject("preCon", preCon);
		mv.addObject("nextCon", nextCon);
		mv.setViewName("info/gywm/zjfc_show");
		return mv;
	}
	
	/**
	 *后台显示联系人列表 
	 * @param pn
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/list")
	public ModelAndView list(@RequestParam(value = "pn",defaultValue="1")Integer pn) throws Exception {
		ModelAndView mv = new ModelAndView();
		PageHelper.startPage(pn, 10);//开始分页,每页10条记录
	    List<Contact> list = contactService.listAll();
		PageInfo page = new PageInfo(list,5);//设置分页信息
		mv.addObject("pageInfo", page);
		mv.setViewName("admin/lxwm/contact_list");
		return mv;
	}
	
	
	/**
	 *跳转到添加新闻页面
	 * @return
	 */
	@RequestMapping("/goAdd")
	public ModelAndView saveView(){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("admin/lxwm/contact_add");
		return mv;

	}
	
	/**
	 * 新增(含文件上传)
	 * @param ntitle
	 * @param ncontent
	 * @param nlevel
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/save",method=RequestMethod.POST)
	public ModelAndView save(@RequestParam(value="TITLE")String title,
            @RequestParam(value="NAME")String name,
            @RequestParam(value="PHONE")String phone, 
            @RequestParam(value="EMAIL")String email,
            @RequestParam(value="ADDRESS")String address,
            @RequestParam(value="POSTCODE")String postcode,
            @RequestParam(value="DESCRIPTION")String description,
            HttpServletRequest request,@RequestParam("file") MultipartFile file) throws Exception {
		
		String persistFileUrl = null;
		 //如果文件不为空，写入上传路径
		if(!file.isEmpty()) {
			//上传文件（目标）路径
			String path = request.getServletContext().getRealPath("/static/uploadfile/");
			//上传文件名
			String filename = file.getOriginalFilename();
			//String fileType = originalFileName.substring(originalFileName.indexOf(".") + 1);//截取文件拓展名.jpg
			persistFileUrl = "static/uploadfile/"+filename;//持久化路径
		    File filepath = new File(path,filename);
			//判断路径是否存在，如果不存在就创建一个
	        if (!filepath.getParentFile().exists()) { 
	        	filepath.getParentFile().mkdirs();
	        }
	        //将上传文件保存到一个目标文件当中
			file.transferTo(new File(path + File.separator + filename));
			
		}
		ModelAndView mv = new ModelAndView();
		//int total = contactService.size();
		Contact con = new Contact();
		//con.setCONTACT_ID(total+1);
		con.setTITLE(title);
		con.setNAME(name);
		con.setPHONE(phone);
		con.setEMAIL(email);
		con.setADDRESS(address);
		con.setPOSTCODE(postcode);
		con.setDESCRIPTION(description);
		con.setMODIFY_TIME(new Date());
		con.setIMG(persistFileUrl);
	    //contactService.addOrUpdateImg(con);
		contactService.save(con);
		mv.setViewName("redirect:list.do");
		return mv;
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	public ModelAndView delete(@RequestParam(value="id")Integer id) throws Exception{
		ModelAndView mv = new ModelAndView();
		contactService.delete(id);
		mv.setViewName("redirect:list.do");
		return mv;
	}
	/**
	 * 去查看个人介绍
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/goContent")
	public ModelAndView goContent(@RequestParam(value="id")Integer id) throws Exception {
		ModelAndView mv = new ModelAndView();
		Contact con = contactService.findById(id);
		mv.addObject("con", con);
		mv.setViewName("admin/lxwm/contact_content");
		return mv;
	}

	/**
	 * 去编辑界面
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/goEdit")
	public ModelAndView goEdit(@RequestParam(value="id")Integer id) throws Exception {
		ModelAndView mv = new ModelAndView();
		Contact  con =contactService.findById(id);
		mv.addObject("contact", con);
		mv.setViewName("admin/lxwm/contact_edit");
		return mv;
	}

	/**
	 * 编辑
	 * @param id
	 * @param title
	 * @param name
	 * @param phone
	 * @param email
	 * @param address
	 * @param postcode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/edit")
	public ModelAndView eidt(@RequestParam(value="CONTACT_ID")Integer id,@RequestParam(value="TITLE")String title,
			                 @RequestParam(value="NAME")String name,@RequestParam(value="PHONE")String phone,
			                 @RequestParam(value="EMAIL")String email,@RequestParam(value="ADDRESS")String address,
			                 @RequestParam(value="POSTCODE")String postcode, @RequestParam(value="DESCRIPTION")String description,
			                 HttpServletRequest request,@RequestParam("file") MultipartFile file) throws Exception {
		String persistFileUrl = null;
		 //如果文件不为空，写入上传路径
		if(!file.isEmpty()) {
			//上传文件（目标）路径
			String path = request.getServletContext().getRealPath("/static/uploadfile/");
			//上传文件名
			String filename = file.getOriginalFilename();
			//String fileType = originalFileName.substring(originalFileName.indexOf(".") + 1);//截取文件拓展名.jpg
			persistFileUrl = "static/uploadfile/"+filename;//持久化路径
		    File filepath = new File(path,filename);
			//判断路径是否存在，如果不存在就创建一个
	        if (!filepath.getParentFile().exists()) { 
	        	filepath.getParentFile().mkdirs();
	        }
	        //将上传文件保存到一个目标文件当中
			file.transferTo(new File(path + File.separator + filename));
			
		}
		    ModelAndView mv = new ModelAndView();
			Contact con = contactService.findById(id);
			con.setTITLE(title);
			con.setNAME(name);
			con.setPHONE(phone);
			con.setEMAIL(email);
			con.setADDRESS(address);
			con.setPOSTCODE(postcode);
			con.setDESCRIPTION(description);
			con.setMODIFY_TIME(new Date());
			con.setIMG(persistFileUrl);
			contactService.edit(con);
			mv.setViewName("redirect:list.do");
		return mv;
	}
	
	/**
	 * 文件上传测试方法
	 * @param request
	 * @param file
	 * @return
	 * @throws Exception
	 */
	/* @RequestMapping(value="/upload",method=RequestMethod.POST)
	 public String upload(HttpServletRequest request,
			//@RequestParam("description") String description,
			@RequestParam("file") MultipartFile file) throws Exception {
		 
	   // System.out.println(description);
	    //如果文件不为空，写入上传路径
		if(!file.isEmpty()) {
			//上传文件（目标）路径
			String path = request.getServletContext().getRealPath("/static/uploadfile/");
			//上传文件名
			String filename = file.getOriginalFilename();
			//String fileType = originalFileName.substring(originalFileName.indexOf(".") + 1);//截取文件拓展名.jpg
			String persistFileUrl = "static/uploadfile/"+filename;//持久化路径
		    File filepath = new File(path,filename);
			//判断路径是否存在，如果不存在就创建一个
	        if (!filepath.getParentFile().exists()) { 
	        	filepath.getParentFile().mkdirs();
	        }
	        //将上传文件保存到一个目标文件当中
			file.transferTo(new File(path + File.separator + filename));
			
			Contact con = new Contact();
	        con.setCONTACT_ID(45);
	        con.setIMG(persistFileUrl);//将文件存储路径持久化数据库
	        contactService.addOrUpdateImg(con);
			return "redirect:list.do";
		} else {
			return "error";
		}
		 
	 }*/
	
	 /**
		 * 
		 * 批量删除
		 * @param request
		 * @param response
		 */
		@RequestMapping("/del")  
		public void batchDeletes(HttpServletRequest request, HttpServletResponse response) {  
		    String items = request.getParameter("delitems");
		    System.out.println(items);  
		    String[] strs = items.split(",");  
		  
		    for (int i = 0; i < strs.length; i++) {  
		        try {  
		            int a = Integer.parseInt(strs[i]);  
		            contactService.delete(a);  
		        } catch (Exception e) {  
		        }  
		    }  
		} 
	
}
